<?php

/**
 * @author dungdhs@gmail.com
 * @copyright 2012
 */

function check_perm($perm){
  global $user;
  
  if (empty($perm)) return false;  
  if ($user->user_info['user_id']==1) return true;
  
  $aUserPerm = perm_load_user_perm($user->user_info['user_id']);
  
  if (is_string($perm)) $aPerm = array($perm);
  else $aPerm = $perm;
  
  foreach ($aPerm as $perm)
  if (isset($aUserPerm[$perm])) return true;
}

function perm_load_user_perm($user_id){
  static $userPerm = null;
  global $database;
  
  if (!isset($userPerm[$user_id])){
    $aPerm = $aRole = array();
    
    if ($user_id==0) $aRole[] = 1;
    else{
      $aRole[] = 2;
      $aRole += perm_load_user_role($user_id);
    }
    
    $res = $database->db_query("SELECT rp_permission FROM role_permissions WHERE rp_role_id IN (%s)", implode(', ', $aRole));
    while ($perm = $database->db_fetch_assoc($res)){
      $aPerm[$perm['rp_permission']] = 1;
    }
    
    $userPerm[$user_id] = $aPerm;
  }
  
  return $userPerm[$user_id];
}

function perm_load_user_role($user_id){
  global $database;
  
  $aRole = array();
  $res = $database->db_query("SELECT ur_role_id FROM user_roles WHERE ur_user_id=%d", $user_id);
  while ($role = $database->db_fetch_assoc($res)) $aRole[$role['ur_role_id']] = $role['ur_role_id'];
  
  return $aRole;
}

?>